import { modifyInfoApi } from "@/api/client/documentManagement/waybillManagement";
import FormHook from "@/hook/formHook";
import { GeneraDataType } from "@/interface";
import { message } from "ant-design-vue";
export default function OperationHook(state: GeneraDataType) {
  const { formState, formDataRef, emit, passData, loading, getChannelOpts, materialOpts, getAllWarehouseCodeOpts } = state;
  const { resetFields } = FormHook({ formState });
  const onFinish = () => {
    const materialNameList = [];
    if (formState.materialQualityId) {
      for (let i = 0; i < formState.materialQualityId.length; i++) {
        const id = formState.materialQualityId[i];
        const { material } = materialOpts.value.find((t: any) => t.id === id);
        materialNameList.push(material);
      }
    }

    const params = {
      ...formState,
      channelId: formState.channelId[1],
      warehouseCode: formState.warehouseCode[1],
      materialQualityId: formState.materialQualityId ? formState.materialQualityId.join(",") : [],
      purchaseInsurance: formState.purchaseInsurance ? 1 : 0,
      materialQualityName: materialNameList.join(","),
      id: passData.value.id,
      channelAllocation: formState.channelId[0]
    };

    loading.value = true;
    modifyInfoApi(params)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("操作成功!");
          emit("submit");
        }
      })
      .finally(() => (loading.value = false));
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const changeCountryHandle = (val: string) => {
    if (val) {
      // getChannelOpts();
      getAllWarehouseCodeOpts();
    }
    formState.channelId = undefined;
    formState.warehouseCode = undefined;
  };
  const changeWarehouseCodeHandle = (val: string) => {
    if (val) {
      getChannelOpts();
    }
    formState.channelId = undefined;
  };
  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    changeCountryHandle,
    changeWarehouseCodeHandle
  };
}
